$(function(){
     // 打开Markdown编辑器
     $("#markdown").click(function () {
        window.location.href = "/markdown";
    });

    layui.use("element", function () {
        var element = layui.element;
    });

    layui.use("layer", function () {
        var layer = layui.layer;
    });

    // 上传头像
    layui.use("upload", function () {
        var upload = layui.upload;
        var uploadInst = upload.render({
            elem: "#upload", //绑定元素
            url: "/upload/photo", //上传接口
            done: function (data) {
                if (data.code === 1) {
                    layer.msg(
                        data.message,
                            {
                                icon: 1,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            },
                            function () {
                                window.location.reload();
                            }
                        );
                } else {
                    layer.msg(
                        data.message,
                            {
                                icon: 5,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            },
                            function () {
                                window.location.reload();
                            }
                        );
                }
            }
        });
    });

    var category = [];

    // 标签
    layui.use(["inputTags"], function () {
        var inputTags = layui.inputTags;
        var cont = inputTags.render({
            elem: "#inputTags", //定义输入框input对象
            content: ["标题一"], //默认标签
            aldaBtn: false, //是否开启获取所有数据的按钮
            done: function (value) {
                //回车后的回调
            }
        });
        category = cont.config.content;
    });

    var lay;
    var layedit;
    // 富文本编辑器
    layui.use("layedit", function () {
        layedit = layui.layedit;
        lay = layedit.build("demo", {
            height: 250, //设置高度
            uploadImage: { url: "/upload/artical_photo", type: "post" }
        }); //建立编辑器
    });

    // 表格的监听
    layui.use("form", function () {
        var form = layui.form;

        //前端验证
        form.verify({
            oldpassword: function (value) {
                if (!/^[A-z0-9]{5,12}$/.test(value)) {
                    return "密码格式不正确";
                }
            },

            newpassword: function (value, item) {
                if (!/^[A-z0-9]{5,12}$/.test(value)) {
                    return "密码格式不正确";
                }
            },

            repassword: function (value) {
                var pwd = $("#r_password").val();
                if (pwd !== value) {
                    return "两次密码不一致";
                }
            }
        });

        //监听提交
        form.on("submit(formDemo)", function (data) {
            // layer.msg(JSON.stringify(data.field));
            $.ajax({
                url: "/modify",
                method: "post",
                data: data.field,
                success: function (msg) {
                    if (msg.code) {
                        layer.msg(
                            msg.message,
                            {
                                icon: 1,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            },
                            function () {
                                window.location.href = "/usercenter";
                            }
                        );
                    } else {
                        layer.msg(
                            msg.message,
                            {
                                icon: 5,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            },
                            function () {
                                window.location.href = "/usercenter";
                            }
                        );
                    }
                }
            });

            return false;
        });

        //修改密码
        form.on("submit(formpassword)", function (data) {
            $.ajax({
                url: "/changepsw",
                method: "get",
                data: data.field,
                success: function (msg) {
                    if (msg.code) {
                        layer.msg(
                            msg.message,
                            {
                                icon: 5,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            },
                            function () { }
                        );
                    } else {
                        layer.msg(
                            msg.message,
                            {
                                icon: 1,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            },
                            function () {
                                window.location.href = "/usercenter";
                            }
                        );
                    }
                }
            });
            return false;
        });

        //发表文章
        form.on("submit(articel)", function (data) {
            if ($("#title").val()) {
                $.ajax({
                    url: "/articel/published",
                    method: "post",
                    data: {
                        author: data.field.id,
                        category,
                        title: data.field.title,
                        content: layedit.getContent(lay),
                        date: new Date()
                    },
                    success: function (msg) {
                        layer.msg(
                            msg.message,
                            {
                                icon: 1,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            },
                            function () {
                                window.location.href = `/articel/Info/${msg.id}`;
                            }
                        );
                    }
                });
            } else {
                var index = layer.alert("标题不能为空", function () {
                    layer.close(index);
                });
            }
            return false;
        });
    
        
        //文章搜索
        form.on('submit(search)',function(data){
            var keyword=data.field;
            function $get(key){
                $.ajax({
                    url:"/articel/search",
                    method:"get",
                    data:keyword,
                    success:function(msg){
                        var str="";
                        msg.forEach(item=>{
                            str+=`
                            <tr>
                                <td>${item.title}</td>
                                <td>${new Date(item.date).toLocaleString('chinese', { hour12: false })}</td>
                                <td>
                                    <button type="button" class="layui-btn arbutton" data-arid="${item._id}">查看</button>
                                    <button type="button" class="layui-btn layui-btn-normal" data-arid="${item._id}">编辑</button>
                                    <button type="button" class="layui-btn layui-btn-danger" data-arid="${item._id}">删除</button>
                                </td>
                            </tr>
                            `
                        })
                        $("#manager").html(str);
                        // 博客管理查看按钮跳转
                        $(".arbutton").click(function(){
                            window.location.href=`/articel/Info/${$(this).attr("data-arid")}`;
                        })
                        $(".layui-btn-normal").click(function(){
                            window.location.href=`/markdown/Modify/${$(this).attr("data-arid")}`;
                        })
                        // 删除
                        $(".layui-btn-danger").click(function(){
                            $.ajax({
                                url:"/articel/delete",
                                method:"get",
                                data:{
                                    keyword:$(this).attr("data-arid")
                                },
                                success:function(msg){
                                    if(msg.code==1){
                                        layer.msg(
                                            msg.message,
                                            {
                                                icon: 1,
                                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                            },
                                            function () {
                                                $get(keyword);
                                            }
                                        );
                                    }else{
                                        layer.msg(
                                            msg.message,
                                            {
                                                icon: 1,
                                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                            },
                                            function () {
                                                $get(keyword);
                                            }
                                        );
                                    }
                                }
                            })
                        })
                    }
                })
            }
            $get(keyword);
            return false;
        })
        

        // 用户管理
        form.on('submit(searchuser)',function(data){
            var keyword=data.field;
            function $get(key){
                $.ajax({
                    url:"/user/search",
                    method:"get",
                    data:keyword,
                    success:function(msg){
                        var str="";
                        msg.message.forEach(item=>{
                            str+=`
                            <tr>
                                <td>${item.userName}</td>
                                <td>${new Date(item.date).toLocaleString('chinese', { hour12: false })}</td>
                                <td>
                                    <button type="button" class="layui-btn layui-btn-danger" data-arid="${item._id}">删除</button>
                                </td>
                            </tr>
                            `
                        })
                        $("#usermanager").html(str);

                        // 删除用户
                        $(".layui-btn-danger").click(function(){
                            
                            $.ajax({
                                url:"/user/delete",
                                method:"get",
                                data:{
                                    keyword:$(this).attr("data-arid")
                                },
                                success:function(msg){
                                    if(msg.code==1){
                                        layer.msg(
                                            msg.message,
                                            {
                                                icon: 1,
                                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                            },
                                            function () {
                                                $get(keyword);
                                            }
                                        );
                                    }else{
                                        layer.msg(
                                            msg.message,
                                            {
                                                icon: 1,
                                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                            },
                                            function () {
                                                $get(keyword);
                                            }
                                        );
                                    }
                                }
                            })
                        })
                    }
                })
            }
            $get(keyword);
            return false;
        })
        


    });

    // 注销
    $("#cancellation").click(function () {
        $.ajax({
            url: "/cancellation",
            method: "get",
            success: function (msg) {
                layer.msg(
                    "退出成功，正在跳转首页",
                    {
                        icon: 1,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    },
                    function () {
                        window.location.href = "/";
                    }
                );
            }
        });
    });

    // 打开信息修改框
    $("#modify").click(function () {
        $("#box").fadeIn("slow");
    });
    // 关闭信息修改框
    $("#close").click(function () {
        $("#box").fadeOut("slow");
    });

    // 表情
    $.Lemoji({
        emojiInput: '#input',
        emojiBtn: '#btn',
        position: 'RIGHTBOTTOM',
        length: 8,
        emojis: {
            qq: {path: '/static/images/qq/', code: ':', name: 'QQ表情'},
            tieba: {path: '/static/images/tieba', code: ';', name: "贴吧表情"},
            emoji: {path: '/static/images/emoji', code: ',', name: 'Emoji表情'}
        }
    });
    // 表情解析
    $('#send').click(function () {
        var content = $('#input').val();
        content = $.emojiParse({
            content: content,
            emojis: [
                {
                    type: 'qq', path: '/static/images/qq/', code: ':'
                }, 
                {
                    path: '/static/images/tieba/',
                    code: ';',
                    type: 'tieba'
                }, 
                {
                    path: '/static/images/emoji/', code: ',', type: 'emoji'
                }
            ]
        });
        $('#test').html(content);
        $.ajax({
            url:"/log/published",
            method:"post",
            data:{
                content,
                date:new Date()
            },
            success:function(msg){
                if(msg.code==1){
                    layer.msg(
                        msg.message,
                        {
                            icon: 1,
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        },
                        function () {
                            $("#input").val("");
                        }
                    );
                }else{
                    layer.msg(
                        msg.message,
                        {
                            icon: 1,
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        },
                        function () {
                            
                        }
                    );
                }
            }
        })
    });

})